<template>
  <div class="app-container calendar-list-container">
    <!-- 搜索工具栏 -->
    <section>
      <so-tool-bar :toolData="toolData" :query="listQuery" @search="search"/>
    </section>
    <!-- 其他操作 -->
    <section class="filter-container">
      <!-- <el-row>
        <el-col :span="12">
            <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
        </el-col>
        <el-col :span="12"> -->
          <section style="float: right">
            <el-button class="filter-item" type="primary" size="small" @click="openForm('add')">发布审批</el-button>
          </section>
        <!-- </el-col>
      </el-row> -->
    </section>
    <!-- 表格 -->
    <el-table :data="tableList" v-loading="loading" element-loading-text="正在查询中。。。" stripe highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="序号" align="center" type="index" width="50"/>
      <el-table-column align="center" label="审批类型" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.moudle_name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.create_time}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="openForm('edit', scope.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <section>
      <so-pagination :query="listQuery" @initList="initList"/>
    </section>
    <!-- 发布活动 -->
    <section>
      <el-dialog :visible.sync="dialog.isShow" width="40%" :show-close="false" :fullscreen="fullscreen" :before-close="beforeClose">
        <el-row slot="title">
          <el-col :span="10" style="padding-top: 5px">
            <span style="font-size: 18px;">{{dialog.title}}</span>
          </el-col>
          <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
          </el-col>
          <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="dialog.isShow = false" style="float: right"></el-button>
          </el-col>
        </el-row>
        <el-form :model="form" ref="createActive" label-width="90px">
          <el-form-item label="类型名称" prop="type_name" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入类型名称" v-model.trim="form.type_name">
            </el-input>
          </el-form-item>
          <el-form-item label="关联模块" prop="moule_id" :rules="filter_rules({required:true})">
            <el-select style="width: 300px;" v-model="form.moule_id" clearable placeholder="请选择" @change="selectChange">
              <el-option v-for="item in options" :key="item.id" :label="item.menu_name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用范围" prop="user_ids">
            <div class="fanwei-box">
              <el-tag v-for="dept in depts" :key="dept.id" style="margin-right:6px;">{{dept.user_name}}</el-tag>
            </div>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openUserTemp"></el-button>
          </el-form-item>
          <el-form-item label="流程设置" prop="approveSets">
            <div style="display:flex;flex-wrap: wrap;">
              <div class="installData-box">
                <div :class="oneData.length>3?'hidden-box':'hidden-box2'">
                  <div class="content-box" v-for="(it,ind) in oneData" :key="ind" @click="openUserTemp2(it)">
                    <img :src="it.portrait?it.portrait:'https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png'" width="50" height="50" alt="">
                    <p>{{ it.user_name }}</p>
                  </div>
                </div>
                <i class="iconfont ali-zuo2" style="margin-right:10px;font-size:24px;transform:scaleX(-1)"></i>
              </div>
              <div class="installData-box">
                <div :class="twoData.length>3?'hidden-box':'hidden-box2'">
                  <div class="content-box" v-for="(it,ind) in twoData" :key="ind" @click="openUserTemp2(it)">
                    <img :src="it.portrait?it.portrait:'https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png'" width="50" height="50" alt="">
                    <p>{{ it.user_name || '一级审批人' }}</p>
                  </div>
                </div>
                <i class="iconfont ali-zuo2" style="margin-right:10px;font-size:24px;transform:scaleX(-1)"></i>
              </div>
              <div class="installData-box">
                <div :class="threeData.length>3?'hidden-box':'hidden-box2'">
                  <div class="content-box" v-for="(it,ind) in threeData" :key="ind" @click="openUserTemp2(it)">
                    <img :src="it.portrait?it.portrait:'https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png'" width="50" height="50" alt="">
                    <p>{{ it.user_name }}</p>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog.isShow = false;form={}">取 消</el-button>
          <el-button type="primary" @click="validate('createActive')">保 存</el-button>
        </span>
      </el-dialog>
    </section>
    <!-- 使用范围 -->
    <section>
      <memberTemp ref="childInit" @saveUsers="saveUsers" @closeTransfer="isShow.transfer = false" :isShow="isShow.transfer"></memberTemp>
    </section>
    <!-- 流程设置 -->
    <section>
      <addApproval ref="settingChild" @saveUsers2="saveUsers2" @closeTransfer2="isShow.transfer2 = false" :isShow2="isShow.transfer2"></addApproval>
    </section>
  </div>
</template>

<script>
import { approve_list, approve_save, approve_edit, approve_updateCloseStatus, 
approve_updateTopStatus, approve_delete, approve_deleteAll, approve_findById,
 } from "@/api/approve";
import { menu_listAll } from "@/api/menu";
import member_transfer from '@/views/addressbook/components/add_member_transfer'
import addApproval from '@/views/approval/components/addApproval'
import { searchTool } from "@/utils";
import SoPagination from "@/components/SoPagination";
import SoToolBar from "@/components/SoToolBar";
import { status_opt, t_active, t_status, toolData } from "./processConfiguration";

export default {
  name: "processConfiguration",
  components: {
    'memberTemp': member_transfer,
    SoPagination,
    SoToolBar,
    addApproval
  },
  data() {
    return {
      toolData: toolData, //工具栏初始化
      loading: false,
      tableList: [],
      isShow: {transfer: false , transfer2: false, everyday_status: 0, everyone_status: 0},
      multipleSelection: [],
      listQuery: { start: 0, limit: 10, total: 0, current: 1 },
      t_active: t_active,
      t_status: t_status,
      status_opt: status_opt,
      dialog: { isShow: false },
      fullscreen: false,
      transfer: { deptShow: false, groupShow: false },
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      form: {},
      oneData:[
        {
          level: 1,
          typeStatus: 1,
          portrait: "https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png",
          user_name: "一级审批人",
          user_ids: ''
        }
      ],
      twoData:[
        {
          level: 2,
          typeStatus: 2,
          portrait: "https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png",
          user_name: "二级审批人",
          user_ids: ''
        }
      ],
      threeData:[
        {
          level: 3,
          typeStatus: 3,
          portrait: "https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png",
          user_name: "三级审批人",
          user_ids: ''
        }
      ],
      depts:[],
      fromStatus: "", //判断是add 还是edit
      inhand_count: 0, //正在进行的数量
      defaultMsg: '',
      options:[],
      index:"",
      approvalList: []
    };
  },
  methods: {
    openUserTemp(){
      this.isShow.transfer = true;
      this.$refs.childInit.openTransfer();
    },
    openUserTemp2(item){
      this.$refs.settingChild.opensettingChild();
      this.isShow.transfer2 = true;
      this.index = item.typeStatus
    },
    // 关联模块选择触发
    selectChange(value){
      let obj = {};
      obj = this.options.find((item)=>{
         return item.id == value;
      });
      this.form.moudle_name = obj.menu_name
    },
    removeRole(it){
      this.oneData.splice(it, 1);
    },
    saveUsers(users){
      for (var i = 0; i < users.length; i++) {
        users[i].id = users[i].id.slice(7)
      }
      this.depts = users;
      this.isShow.transfer = false;
    },
    saveUsers2(users){
      if (this.index == 1) {
        for (var i = 0; i < users.length; i++) {
          this.$set(users[i], "typeStatus", 1);
          users[i].id = users[i].id.slice(7)
        }
        this.oneData = users.slice()
      }
      if (this.index == 2) {
        for (var i = 0; i < users.length; i++) {
          users[i].id = users[i].id.slice(7)
          this.$set(users[i], "typeStatus", 2);
        }
        this.twoData = users.slice()
      }
      if (this.index == 3) {
        for (var i = 0; i < users.length; i++) {
          users[i].id = users[i].id.slice(7)
          this.$set(users[i], "typeStatus", 3);
        }
        this.threeData = users.slice()
      }
      this.isShow.transfer2 = false;
    },
    beforeClose(done){
      done()
    },
    async saveObj() {
      try {
        const params = {...this.form, company_id: localStorage.getItem("companyId") - 0};
        this.loading = true;
        const { data } = this.fromStatus == "add" ? await approve_save(params) : await approve_edit(params);
        this.loading = false;
        if (data.status == 100) {
          this.$message.success(this.fromStatus == "add" ? "添加成功" : "编辑成功" );
          this.initList();
        }
      } catch (error) {
        console.log(error,'error')
      }
    },
    validate(e) {
      this.$refs[e].validate(valid => {
        if (valid) {
          let ids = "", oneIds = "", groupIds = "", roleIds = "", oneData = {}, twoData = {}, threeData = {};
          if (this.depts && this.depts.length > 0) {
            ids = this.depts.map(item => item.id).join();
          }
          this.form.user_ids = ids
          if (!this.form.user_ids) {
            this.$message.warning("请选择使用范围");
            return;
          }
          if (this.oneData[0].dept_name || this.twoData[0].dept_name || this.threeData[0].dept_name) {
            
          } else {
            this.$message.warning("至少要设置一个审批");
            return;
          }

          if (this.oneData && this.oneData.length > 0) {
            oneIds = this.oneData.map(item => item.id).join();
          }

          if (this.twoData && this.twoData.length > 0) {
            groupIds = this.twoData.map(item => item.id).join();
          }

          if (this.threeData && this.threeData.length > 0) {
            roleIds = this.threeData.map(item => item.id).join();
          }


          if (this.fromStatus == "add") {
            if (oneIds) {
              oneData = { user_ids: oneIds || '', role_ids: "", dept_ids:"", level: 1 }
            }

            if (groupIds) {
              twoData = { user_ids: groupIds || '', role_ids: "", dept_ids:"", level: 2 }
            }

            if (roleIds) {
              threeData = { user_ids: roleIds || '', role_ids: "", dept_ids:"", level: 3 }
            }

            let approveSets = []
            if (oneIds && groupIds && roleIds) {
              approveSets.push(oneData,twoData,threeData)
            } else if (oneIds) {
              approveSets.push(oneData)
            } else if (groupIds) {
              approveSets.push(twoData)
            } else if (roleIds) {
              approveSets.push(threeData)
            }

            this.form.approveSets = JSON.stringify(approveSets)
          }
          console.log(this.form.approveSets);

          if (this.fromStatus == "edit") {
            if (oneIds) {
              if (this.approvalList[0]) {
                this.approvalList[0].user_ids = oneIds 
              } else {
                this.approvalList[0] = { user_ids: oneIds || '', role_ids: "", dept_ids:"", level: 1 }
              }
            } 

            if (groupIds) {
              if (this.approvalList[1]) {
                this.approvalList[1].user_ids = groupIds 
              } else {
                this.approvalList[1] = { user_ids: groupIds || '', role_ids: "", dept_ids:"", level: 2 }
              }
            }

            if (roleIds) {
              if (this.approvalList[2]) {
                this.approvalList[2].user_ids = roleIds 
              } else {
                this.approvalList[2] = { user_ids: roleIds || '', role_ids: "", dept_ids:"", level: 3 }
              }
            }
            this.form.approveSets = JSON.stringify(this.approvalList)
          }
          // return
          this.saveObj();
          this.dialog.isShow = false;
        } else {
          return false;
        }
      });
    },
    async delRows(){//批量删除
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      try {
        const res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          const { data } = await active_deleteAll({array: ids});
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    async delRow(row) {//删除
      try {
        let res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          let { data } = await approve_delete(row);
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {}
    },
    async openForm(e, row) {//打开活动面板
      if (e == "add") {
        this.fromStatus = "add";
        this.$refs.childInit.openTransfer();
        this.form = {}; //清空数据
        this.depts = []; //清空数据
        this.dialog = {isShow: true, title: "发布审批" };
        this.oneData = [
          {
            level: 1,
            typeStatus: 1,
            portrait: "https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png",
            user_name: "一级审批人",
            user_ids:''
          }
        ];
        this.twoData = [
          {
            level: 2,
            typeStatus: 2,
            portrait: "https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png",
            user_name: "二级审批人",
            user_ids: ''
          }
        ],
        this.threeData = [
          {
            level: 3,
            typeStatus: 3,
            portrait: "https://saic-public.oss-cn-shanghai.aliyuncs.com/头像.png",
            user_name: "三级审批人",
            user_ids: ''
          }
        ]
      } else {
        const {data} = await approve_findById({id: row.id});
        if(data.status != 100){
          this.$message.warning('数据获取异常')
          return;
        }
        this.fromStatus = "edit";
        this.dialog = {isShow: true, title: "编辑审批" };
        this.form = data.data
        this.depts = data.data.user_ids
        let approveSets = data.data.approveSets
        this.approvalList = data.data.approveSets

        if (approveSets[0]) {
          if (approveSets[0].user_ids !== null) {
            approveSets[0].user_ids.forEach(element => {
                this.$set(element,'typeStatus',1)
            });
            this.oneData = approveSets[0].user_ids
          } else {
            this.oneData = this.oneData
          } 
        }

        if (approveSets[1]) {
          if (approveSets[1].user_ids.length) {
            approveSets[1].user_ids.forEach(element => {
              this.$set(element,'typeStatus',2)
            });
            this.twoData = approveSets[1].user_ids
          } else {
            this.twoData = this.twoData
          }
        }

        if (approveSets[2]) {
          if (approveSets[2].user_ids.length) {
            approveSets[2].user_ids.forEach(element => {
              this.$set(element,'typeStatus',3)
            });
            this.threeData = approveSets[2].user_ids
          } else {
            this.threeData = this.threeData
          }
        }
      }
    },
    handleSelectionChange(e) {
      this.multipleSelection = e;
    },
    search() {//搜索
      let keyWords = {key: "searchDate", names: ["active_start_time", "active_end_time"]};
      this.listQuery = searchTool(this.listQuery, keyWords);
      this.initList();
    },
    async initList() {
      this.loading = true;
      const query = {...this.listQuery, company_id: localStorage.getItem("companyId") - 0};
      const { data } = await approve_list(query);
      this.loading = false;
      if (data.status == 100) {
        this.tableList = data.data.rows;
        this.listQuery.total = data.data.results;
      }
    },
    async menuList() {
      this.options = [
        {
          id: 1,
          menu_name: "优化建议"
        },
        {
          id: 2,
          menu_name: "生育福利"
        },
        {
          id: 3,
          menu_name: "结婚福利"
        }
      ]
      // this.loading = true;
      // const query = { company_id: localStorage.getItem("companyId") - 0 };
      // const { data } = await menu_listAll(query);
      // this.loading = false;
      // if (data.status == 100) {
      //   this.options = data.data.rows;
      // }
    }
  },
  created() {
    this.menuList()
    this.initList();
  }
};
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
span {
  font-size: 13px;
  color: $color;
}
.ali-zhiding{
  color: #009900;
  font-size: 20px;
}
.fanwei-box {
  max-height: 75px;
  overflow-x: hidden;
  overflow-y: scroll;
  cursor: pointer;
}
.fanwei-box::-webkit-scrollbar {
    display: none;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
.installData-box {
  display: flex;
  // flex-wrap: wrap;
  // align-items: center;
  .hidden-box{
    max-width: 180px;
    position:relative;
    display: -webkit-box;
    overflow-x:scroll;
    overflow-y:hidden;
    cursor: pointer;
  }
  .hidden-box2 {
    max-width: 180px;
    cursor: pointer;
  }
  .hidden-box2::-webkit-scrollbar {
    display: none;
  }
  .content-box {
    padding-right: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    img {
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .icon-close-box{
    position: absolute;
    top: 0px;
    right: 10px;
    color: #ccc;
  }
}
</style>
